<?php
class Controller_Amazonsales extends Controller
{
    public function action_index()
    {
        if( PHP_SAPI !== 'cli' ) return;

        set_time_limit(0);                                                                                              //防超时
        ignore_user_abort(true);

        $count = 0;                                                                                                     //导入计数
        $page = 1;                                                                                                      //当前分页
        $maxDate = date('Y-m-d', $_SERVER['REQUEST_TIME']);
        $nowDate = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
        echo "交期导入开始 : {$nowDate} \n";

        $sql = 'SELECT
            DATE_FORMAT(`add_time`, "%Y-%m-%d") maxDate
        FROM
            `amz_sales`
        ORDER BY
            `id` DESC 
        LIMIT 1';
        $minDate = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();                                    //读取数据库最大时间
        $minDate = empty($minDate) ? date('Y-m-d', $_SERVER['REQUEST_TIME'] - 2592000) : $minDate[0]['maxDate'];        //生成最小范围的过滤条件

        $sql = "SELECT
            `products`.SellerSKU_Clean sku,
            SUM(`products`.QuantityOrdered) c, 
            DATE_FORMAT(`orders`.PurchaseDate, '%Y-%m-%d') `date`
        FROM
            `orders`
                LEFT JOIN `products` ON
                    `products`.AmazonOrderId = `orders`.AmazonOrderId
        WHERE
            `orders`.PurchaseDate >= '{$minDate}'
        AND `orders`.PurchaseDate < '{$maxDate}'
        AND `orders`.OrderStatus <> 'Pending'
        GROUP BY
            `products`.SellerSKU_Clean, DATE_FORMAT(`orders`.PurchaseDate, '%Y-%m-%d')";
        while( stagerpc::getAmazonSkuSales($sql . ' LIMIT ' . ($page++ - 1) * 100 . ', 100', $data) ) {
            foreach($data as &$v) {
                $v = '("' . join('","', tool::slashesDeep($v)) . "\", \"{$nowDate}\")";
                $count += 1;
            }
            $data = 'INSERT INTO `amz_sales` (
                `sku`, `sale`, `count_date`, `add_time`
            ) VALUES ' . join(',', $data);
            DB::query(Database::INSERT, $data)->execute('newerp');
        }

        $nowDate = time() - $_SERVER['REQUEST_TIME'];
        echo "交期导入结束 : 导入 {$count} 条, 耗时 {$nowDate} 秒\n";
    }
}